package com.bianmaba.spring.supports.mvc.advice;

import com.bianmaba.spring.supports.data.beans.basc.PageableResult;
import com.bianmaba.spring.supports.data.beans.basc.Result;
import com.bianmaba.spring.supports.mvc.annotations.JSON;
import com.bianmaba.spring.supports.mvc.annotations.StrutsJSON;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class StrutsJsonResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        boolean supported = returnType.hasMethodAnnotation(JSON.class) || returnType.hasParameterAnnotation(JSON.class) || returnType.hasMethodAnnotation(StrutsJSON.class) || returnType.hasParameterAnnotation(StrutsJSON.class);
        return supported;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body == null) {
            Result result = new Result(false);
            result.setData(body);
            return result;
        } else if (body.getClass().isAssignableFrom(PageImpl.class)) {
            PageableResult result = new PageableResult((PageImpl) body);
            return result;
        } else if (!body.getClass().isAssignableFrom(Result.class)) {
            Result result = new Result(true);
            result.setData(body);
            return result;
        }
        return body;
    }
}